package com.cchc.k8s.kernel;

import com.cchc.k8s.request.CreateIngressRequest;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.models.*;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * file：IngressBuilder.java
 * description:
 * date: 2021-10-12 17:21
 * author: wenrui
 * version: 1.0
 */
@Component
public class IngressBuilder {

    public ExtensionsV1beta1Ingress builder(CreateIngressRequest request) {
        ExtensionsV1beta1Ingress ingress = new ExtensionsV1beta1Ingress();
        ingress.apiVersion("extensions/v1beta1").kind("Ingress");

        // metadata
        Map<String,String> metaMap = new HashMap<>();
        metaMap.put("nginx.ingress.kubernetes.io/use-regex", "true");
        metaMap.put("nginx.ingress.kubernetes.io/rewrite-target", "/");
        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta()
                .name(request.getIngressName() + "-igs")
                .annotations(metaMap);

        ingress.metadata(v1ObjectMeta);
        // spec
        ExtensionsV1beta1IngressSpec spec = new ExtensionsV1beta1IngressSpec();
        // rules
        List<ExtensionsV1beta1IngressRule> ruleList = new ArrayList<>();
        List<ExtensionsV1beta1IngressTLS> tlsList = new ArrayList<>();
        for (CreateIngressRequest.IngressRule rule : request.getRuleList()) {
            ExtensionsV1beta1IngressRule ingressRule = new ExtensionsV1beta1IngressRule();
            ingressRule.host(rule.getHost());
            if (request.getHttps()) {
                // tls
                ExtensionsV1beta1IngressTLS tls = new ExtensionsV1beta1IngressTLS();
                tls.addHostsItem(rule.getHost());
                tls.secretName("tls-secret");
                tlsList.add(tls);
            }
            // paths
            ExtensionsV1beta1HTTPIngressRuleValue value = new ExtensionsV1beta1HTTPIngressRuleValue();
            List<ExtensionsV1beta1HTTPIngressPath> pathList = new ArrayList<>();
            for (CreateIngressRequest.IngressRule.RulePath rulePath : rule.getPathList()) {
                ExtensionsV1beta1HTTPIngressPath path = new ExtensionsV1beta1HTTPIngressPath();
                ExtensionsV1beta1IngressBackend backend = new ExtensionsV1beta1IngressBackend();
                backend.serviceName(rulePath.getServiceName() + "-svc").servicePort(new IntOrString(rulePath.getServicePort()));
                path.path(rulePath.getPath()).backend(backend);
                pathList.add(path);
            }
            value.paths(pathList);
            ingressRule.http(value);
            ruleList.add(ingressRule);
        }
        spec.rules(ruleList);
        spec.tls(tlsList);
        ingress.spec(spec);
        return ingress;
    }
}
